package com.yunyike.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yunyike.constants.CartConstants;
import com.yunyike.constants.CommonConstant;
import com.yunyike.dto.SettlementDTO;
import com.yunyike.dto.cart.CartDTO;
import com.yunyike.exception.BadRequestException;
import com.yunyike.mapper.CouponMapper;
import com.yunyike.model.Coupon;
import com.yunyike.model.User;
import com.yunyike.redis.JedisManager;
import com.yunyike.service.ICouponService;

/**
 * @author zhengqiang.shi
 * 2015年11月26日 下午10:18:14
 */
@Service("couponServiceImpl")
public class CouponServiceImpl implements ICouponService {

	private static Logger log = LoggerFactory.getLogger(CouponServiceImpl.class);
	
	@Autowired
	private CouponMapper couponMapper;
	
	/**
	 * 为用户发优惠券
	 */
	public int addCoupon(Coupon coupon) {
		log.info("save coupon...,{}",coupon);
		
		int result;
		try {
			result = couponMapper.insert(coupon);
		} catch (Exception e) {
			log.info("save coupon failed,message:"+e.getMessage(),e);
			return CommonConstant.NUMBER_0;
		}
		log.info("save coupon end,result:"+result);
		return result;
	}

	/**
	 * 根据条件 获取优惠券
	 */
	public List<Coupon> findCouponByCondition(Coupon coupon) {
		
		log.info("findAvailiableCoupons...{}:",coupon);
		
		List<Coupon> list = null;
		try {
			list = couponMapper.findCouponsByCondition(coupon);
		} catch (Exception e) {
			log.error("findAvailiableCoupons failed.message:"+e.getMessage(),e);
			return null;
		}

		log.info("findAvailiableCoupons end.");
		return list;
		
	}

	/**
	 * 结算页获取可用优惠券数量
	 */
	public Integer findCouponQtyBySettlement(User user, com.yunyike.dto.cart.CartDTO cartDTO) {
		
		// 商品金额
		BigDecimal totalMerchandisePrice = cartDTO.getTotalMerchandisePrice();
		
		// 获取所有可用优惠券
		Coupon coupon = new Coupon();
		coupon.setUserId(user.getUserId());
		coupon.setCouponStatus(CommonConstant.NUMBER_0);
		
		List<Coupon> coupons = couponMapper.findAvailiableCoupons(coupon);
		if(coupons == null || coupons.isEmpty()){
			log.info("no coupons.");
			return CommonConstant.NUMBER_0;
		}

		// 获取数量
		Integer qtyByCoupons = qtyByCouponsBySettlement(coupons, totalMerchandisePrice);
		
		log.info("qtyByCoupons:{}",qtyByCoupons);
		
		return qtyByCoupons;
	}

	private Integer qtyByCouponsBySettlement(List<Coupon> coupons, 
			BigDecimal totalMerchandisePrice){
		int coupon0Qty = 0;
		for (Coupon coupon : coupons) {
			Integer couponType = coupon.getCouponType();
			Double couponUsePrice = coupon.getCouponUsePrice();
			switch (couponType) {
			// 优惠券
			case CommonConstant.NUMBER_0:
				if(couponUsePrice <= totalMerchandisePrice.doubleValue()){
					coupon0Qty ++;
				}
				break;
			}
		}
		return coupon0Qty;
	}
	
	private List<Coupon> couponsBySettlement(List<Coupon> coupons, 
			BigDecimal totalMerchandisePrice){
		List<Coupon> list = new ArrayList<Coupon>();
		for (Coupon coupon : coupons) {
			Integer couponType = coupon.getCouponType();
			Double couponUsePrice = coupon.getCouponUsePrice();
			switch (couponType) {
			// 优惠券
			case CommonConstant.NUMBER_0:
				if(couponUsePrice <= totalMerchandisePrice.doubleValue()){
					list.add(coupon);
				}
				break;
			}
		}
		return list;
	}
	
	public void useCoupon(User user, String couponId, Integer couponType, String sessionId) {
		
		// settlement redis key
		log.info("----->> generator settlement key...");
		String settlementKey = CartConstants.settlementKey(sessionId);
		log.info("settlement key:"+settlementKey);
		
		// current settlement data
		SettlementDTO settlementDTO = (SettlementDTO)JedisManager.getObject(settlementKey);
		// 获取当前已选择的优惠券
		List<Coupon> couponList = settlementDTO.getCouponList();
		if(couponList == null){
			couponList = new ArrayList<Coupon>();
		}
		
		if(StringUtils.isBlank(couponId)){
			// 取消已经选择的优惠券
			for (Coupon coupon : couponList) {
				Integer couponTypeSettlement = coupon.getCouponType();
				if(couponTypeSettlement.intValue() == couponType.intValue()){
					couponList.remove(coupon);
					break;
				}
			}
		}else{
			// 选择优惠券
			Coupon needUseCoupon = couponMapper.selectByPrimaryKey(couponId);
			if(needUseCoupon == null){
				throw new BadRequestException("couponId:"+couponId+"\t not exist in db");
			}
			
			if(!needUseCoupon.getUserId().equals(user.getUserId())){
				throw new BadRequestException("couponId:"+couponId+"\t not belong to current user,userId:"+user.getUserId());
			}
			
			for (Coupon coupon : couponList) {
				Integer couponTypeSettlement = coupon.getCouponType();
				if(couponTypeSettlement.intValue() == needUseCoupon.getCouponType().intValue()){
					couponList.remove(coupon);
					break;
				}
			}
			
			// 添加到使用的优惠券列表中
			couponList.add(needUseCoupon);
		}
		
		// set to redis
		try {
			settlementDTO.setCouponList(couponList);
			JedisManager.setObject(settlementKey, CartConstants.SETTLEMENT_OUT_TIME, settlementDTO);
		} catch (Exception e) {
			log.error("useCoupon has error,message:"+e.getMessage(),e);
		}
	}

	public List<Coupon> findCouponsBySettlement(User user,CartDTO cartDTO) {
		
		// 商品金额
		BigDecimal totalMerchandisePrice = cartDTO.getTotalMerchandisePrice();
		
		// 获取所有可用优惠券
		Coupon coupon = new Coupon();
		coupon.setUserId(user.getUserId());
		coupon.setCouponStatus(CommonConstant.NUMBER_0);
		
		List<Coupon> coupons = couponMapper.findAvailiableCoupons(coupon);
		if(coupons == null || coupons.isEmpty()){
			log.info("no coupons.");
			return null;
		}

		// 获取满足条件的优惠券
		List<Coupon> list = couponsBySettlement(coupons, totalMerchandisePrice);
		
		return list;
	}
	
	public Map<String, Integer> findAvailiableCouponQty(User user) {
		
		// 初始化返回参数
		Map<String, Integer> couponQtyMap = new HashMap<String, Integer>();
		couponQtyMap.put("0", 0);
		couponQtyMap.put("1", 0);
		
		// 获取所有可用优惠券
		Coupon coupon = new Coupon();
		coupon.setUserId(user.getUserId());
		coupon.setCouponStatus(CommonConstant.NUMBER_0);
		
		List<Coupon> coupons = couponMapper.findCouponsByCondition(coupon);
		if(coupons == null || coupons.isEmpty()){
			log.info("no coupons.");
			return couponQtyMap;
		}
		
		int coupon0Qty = 0;
		int coupon1Qty = 0;
		for (Coupon coupon2 : coupons) {
			Integer couponType = coupon2.getCouponType();	// 券类型
			
			Date couponStartDate = coupon2.getCouponStartDate();	// 开始日期
			Date couponEndDate = coupon2.getCouponEndDate();	// 结束日期
			Date currentDate = new Date();	// 当前日期
			
			if(currentDate.after(couponStartDate) && currentDate.before(couponEndDate)){
				switch (couponType) {
				// 物流券
				case CommonConstant.NUMBER_0:
					coupon0Qty ++;
					break;
					
					// 现金券
				case CommonConstant.NUMBER_1:
					coupon1Qty ++;
					break;
			}
			}
		}
		
		couponQtyMap.put("0", coupon0Qty);
		couponQtyMap.put("1", coupon1Qty);
		
		return couponQtyMap;
	}

	public int updateCoupon(Coupon coupon) {
		return couponMapper.updateByPrimaryKeySelective(coupon);
	}
}
